/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../utils/js.ts" />
/// <reference path="../log/log-manager.ts" />
/// <reference path="./database.ts" />

namespace lcc {

const TAG = "lcc/database/database-manager.ts";

/**
 * @zh
 * 数据库tick时间
 */
export let DATABASE_TICKTIME = 1;

/**
 * @zh
 * 数据库对象映射表
 */
export let DATABASES:{[key:string]:Database} = js.createMap();

/**
 * @zh
 * 数据库管理器<br/>
 * 主要管理游戏连接的数据库
 */
class DatabaseManager {
	
	/**
     * @zh
	 * 数据库类型表
	 */
	private _dbTypes:{[key:number]:typeof Database} = js.createMap();
    
	/**
     * @zh
	 * 是否使用心跳
	 */
	private _useHeart:boolean = false;

	/**
     * @zh
	 * 注册数据库类型
     * 
	 * @param type - 类型
	 * @param value - 数据库Class
	 */
	public registerDatabaseType(type:DatabaseType, value:typeof Database){
		this._dbTypes[type] = value;
		DEBUG.DATABASE && logMgr.debug(TAG, `registerDatabaseType ${type}`);
	}

	/**
     * @zh
	 * 安装心跳
	 */
	private setupHeartTick(){
		if(!this._useHeart && !js.isEmptyMap(DATABASES)){
			timerMgr.addTimer(DATABASE_TICKTIME, this.onHeartTick.bind(this),{
                group : "lcc.DatabaseManager", 
                key : "tick",
                loop : true
            });
			this._useHeart = true;
			DEBUG.DATABASE && logMgr.debug(TAG, `setupHeartTick tick ${DATABASE_TICKTIME}`);
		}
	}

	/**
     * @zh
	 * 删除心跳
	 */
	private deleteHeartTick(){
		if(this._useHeart && js.isEmptyMap(DATABASES)){
			timerMgr.removeTimer({
                group : "lcc.DatabaseManager", 
                key : "tick"
            });
			this._useHeart = false;
			DEBUG.DATABASE && logMgr.debug(TAG, `deleteHeartTick tick`);
		}
	}
	
	/**
     * @zh
	 * 心跳回调
	 */
	private onHeartTick(dt:number){
		for (let dbname of Object.keys(DATABASES)){
			let database = DATABASES[dbname];
			if(database){
				database.onUpdate(dt);
			}
		}
	}
    
	/**
     * @zh
	 * 添加数据库
     * 
	 * @param dbname - 数据库名称
	 * @param type - 类型
	 * @param config - 配置对象
	 */
	public async addDatabase(dbname:string, type:DatabaseType, config:any = js.createMap()){
		DEBUG.DATABASE && logMgr.debug(TAG, `addDatabase ${dbname} ${type} ${JSON.stringify(config)}`);
		if(DATABASES[dbname]){
			logMgr.error(TAG, `database [${dbname}] conflict!`);
		}else{
			let dbType = this._dbTypes[type];
			if(!dbType){
				logMgr.error(TAG, `database type [${type}] not found!`);
			}else{
				let database = new dbType(dbname, DatabaseType.MYSQL);
				database.config(config);
				let r = await database.connect();
				if(r){
					DATABASES[dbname] = database;
					this.setupHeartTick();
					DEBUG.DATABASE && logMgr.debug(TAG, `addDatabase ${dbname} success`);
					return database;
				}else{
					DEBUG.DATABASE && logMgr.debug(TAG, `addDatabase ${dbname} failure`);
				}
			}
		}
	}

    /**
     * @zh
     * 获得指定数据库
     * 
     * @param dbname - 数据库名称
     */
    public getDatabase(dbname:string){
        return DATABASES[dbname];
	}
	
	/**
     * @zh
	 * 移除指定数据库
     * 
	 * @param dbname - 数据库名称
	 */
	public async removeDatabase(dbname:string){
		DEBUG.DATABASE && logMgr.debug(TAG, `removeDatabase ${dbname}`);
		let database = DATABASES[dbname];
		if(database){
			delete DATABASES[dbname];
			this.deleteHeartTick();
			await database.disconnect();
			DEBUG.DATABASE && logMgr.debug(TAG, `removeDatabase ${dbname} success`);
		}
	}
    
    /**
     * @zh
     * 移除所有数据库
     */
    public async removeAllDatabases(){
        for(let dbname of Object.keys(DATABASES)){
            await this.removeDatabase(dbname);
        }
    }
};

/**
 * @zh
 * 数据库管理器对象
 */
export const dbMgr = new DatabaseManager();

}
